/**
 * 
 */
package fb.test.uitl;

import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * @author hoannguyen
 * 
 */
public final class LogUtils {

	/**
	 * Logging file name
	 */
	private static final String fileName = "D:\\fblogging.log";
	
	/**
	 * The logger
	 */
	private static Logger logger = Logger.getLogger("MyLogger");

	/**
	 * To log the given exception to both file and console
	 * @param e
	 */
	public static void log(Exception e) {

		try {

			// formatter
			SimpleFormatter formatter = new SimpleFormatter();
			
			// Create FileHandler
			FileHandler fileHandler = new FileHandler(fileName);
			fileHandler.setFormatter(formatter);
			logger.addHandler(fileHandler);

			// Create ConsoleHandler
			ConsoleHandler consoleHandler = new ConsoleHandler();
			consoleHandler.setFormatter(formatter);
			logger.addHandler(consoleHandler);

			// Logging
			printStackTrace(e);
			
		} catch (SecurityException e1) {
			printStackTrace(e1);
		} catch (IOException e2) {
			printStackTrace(e2);
		}
	}

	/**
	 * To print the stack trace of the given exception with the logger 
	 * @param e
	 */
	private static void printStackTrace(Exception e) {
		
		for (StackTraceElement element : e.getStackTrace()) {
			logger.info(element.toString());
		}
	}
}
